/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.contract.app;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.contract.dto.ContractHistoryTradeDTO;
import com.pig4cloud.pigx.contract.dto.ContractStatisticsTimeDTO;
import com.pig4cloud.pigx.contract.entity.ContractTrade;
import com.pig4cloud.pigx.contract.service.ContractTradeService;
import com.pig4cloud.pigx.contract.utils.ContractUtils;
import com.pig4cloud.pigx.contract.vo.ContractStatisticsHandlingFeeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 成交记录表
 *
 * @date 2022-08-11 10:08:52
 */
@RestController
@AllArgsConstructor
@RequestMapping("/app/trade")
@Api(value = "contracttrade", tags = "app成交记录管理")
public class AppContractTradeController {

    private final ContractTradeService contractTradeService;
    private final ContractUtils contractUtils;

    /**
     * 分页查询
     *
     * @param page          分页对象
     * @param contractTrade 成交记录表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_view')")
    public R getContractTradePage(Page page, ContractTrade contractTrade) {
        return R.ok(contractTradeService.page(page, Wrappers.query(contractTrade)));
    }

    /**
     * 通过id查询成交记录表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_view')")
    public R getById(@PathVariable("id") Long id) {
        ContractTrade trade = contractTradeService.getById(id);

        // 设置精度
        contractUtils.setScaleBySymbol(trade, trade.getSymbolName());

        // 清空localThread币对缓存
        ContractUtils.removeSymbolThreadCache();
        return R.ok(trade);
    }

    /**
     * 获取历史成交记录
     *
     * @return
     */
    @ApiOperation(value = "获取历史成交记录", notes = "获取历史成交记录")
    @GetMapping("/page/history")
    public R getHistoryTrade(Page page, ContractHistoryTradeDTO dto) {
        PigxUser pigxUser = SecurityUtils.getUser();
        dto.setUserId(pigxUser.getId());
        return contractTradeService.getHistoryTrade(page, dto);
    }

    /**
     * 财务 -> 手续费统计报表
     *
     * @param dto 统计时间区间
     * @return R
     */
    @ApiOperation(value = "手续费统计报表", notes = "手续费统计报表")
    @GetMapping("/statistics/handlingFee")
    public R<List<ContractStatisticsHandlingFeeVO>> statisticsHandlingFee(ContractStatisticsTimeDTO dto) {
        try {
            return R.ok(contractTradeService.statisticsHandlingFee(dto.getStartTime(), dto.getEndTime()));
        } catch (Exception e) {
            e.printStackTrace();
            return R.failed("查询失败");
        }
    }

    /**
     * @param dto
     * @param response
     * @return
     */
    @ApiOperation(value = "手续费统计报表-导出", notes = "手续费统计报表")
    @GetMapping(value = "/statistics/handlingFee/export", produces = "application/octet-stream")
    public R<String> excel(ContractStatisticsTimeDTO dto, HttpServletResponse response) {
        HSSFWorkbook wb = contractTradeService.excel(dto.getStartTime(), dto.getEndTime());
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //代表的是Excel文件类型
            response.setHeader("Content-Disposition", "attachment;filename=手续费统计报表.xls");
            wb.write(out);
            return R.ok("导出成功");
        } catch (IOException e) {
            return R.failed("导出失败");
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
                wb.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
